/*
 * @Author: liaoxing
 * @Date: 2022-03-01 16:20:32
 * @LastEditors: liaoxing
 * @LastEditTime: 2022-03-01 16:34:01
 * @Description: liaoxing created
 * @FilePath: \pin-xin-admin\src\utils\downBase64.js
 */

function dataURLtoBlob(dataurl) {
  var arr = dataurl.split(','),
  mime = arr[0].match(/:(.*?);/)[1],
  bstr = window.atob(arr[1]),
  n = bstr.length, 
  u8arr = new Uint8Array(n);
  while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
}

function downloadFile(url, name){
  if (!name) {
    alert("无文件名")
    return
  }
  var a = document.createElement("a")
  a.setAttribute("href",url)
  a.setAttribute("download",name)
  a.setAttribute("target","_blank")
  let clickEvent = document.createEvent("MouseEvents");
  clickEvent.initEvent("click", true, true);  
  a.dispatchEvent(clickEvent);
}

function downloadFileByBase64(base64, name){
  console.log(1)
  var myBlob = dataURLtoBlob(base64)
  console.log(2)
  var myUrl = URL.createObjectURL(myBlob)
  downloadFile(myUrl,name)
}

export default downloadFileByBase64